<template>
  <div class="products-container">
    <div class="sidebar">
      <h3 class="sidebar-title">商品分类</h3>
      <ul class="category-list">
        <li 
          :class="{ active: selectedCategoryId === null }"
          @click="selectCategory(null)"
        >
          全部商品
        </li>
        <li 
          v-for="category in categoryList" 
          :key="category.id"
          :class="{ active: selectedCategoryId === category.id }"
          @click="selectCategory(category.id)"
        >
          {{ category.name }}
        </li>
      </ul>
    </div>
    
    <div class="main-content">
      <div class="products-header">
        <h2>
          <template v-if="route.query.keyword">
            搜索"{{ route.query.keyword }}"的结果
          </template>
          <template v-else>
            全部商品
          </template>
        </h2>
        <div class="filter-options">
          <el-select v-model="sortOption" placeholder="排序方式" @change="loadProducts">
            <el-option label="默认排序" value="default" />
            <el-option label="价格从低到高" value="priceAsc" />
            <el-option label="价格从高到低" value="priceDesc" />
            <el-option label="销量优先" value="salesDesc" />
          </el-select>
        </div>
      </div>
      
      <el-empty v-if="productList.length === 0" description="暂无商品" />
      
      <div class="products-grid">
        <div 
          v-for="product in productList" 
          :key="product.id" 
          class="product-card"
          @click="goToProductDetail(product.id)"
        >
          <div class="product-img">
            <img :src="product.imgs ? baseURL + product.imgs.split(',')[0] : ''" alt="商品图片">
          </div>
          <div class="product-info">
            <h3 class="product-name">{{ product.name }}</h3>
            <div class="product-price">
              <span class="price">¥{{ (product.specPrice * product.discount).toFixed(2) }}</span>
              <span class="original-price" v-if="product.discount < 1">¥{{ product.specPrice }}</span>
            </div>
            <div class="product-sales">已售 {{ product.sales || 0 }}</div>
          </div>
        </div>
      </div>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();
const categoryList = ref([]);
const productList = ref([]);
const selectedCategoryId = ref(null);
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);
const sortOption = ref('default');
const baseURL = 'http://localhost:9191'; // 添加API基础URL常量

// 获取分类列表
const fetchCategories = async () => {
  try {
    const result = await request.get('/api/category');
    if (result.code === '200') {
      categoryList.value = result.data;
    } else {
      ElMessage.error('获取分类列表失败');
    }
  } catch (error) {
    console.error('获取分类失败:', error);
    ElMessage.error('获取分类列表失败');
  }
};

// 加载商品列表
const loadProducts = async () => {
  try {
    // 获取URL中的搜索关键词
    const keyword = route.query.keyword || '';
    
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      searchText: keyword,
      categoryId: selectedCategoryId.value
    };
    
    const result = await request.get('/api/good/productsWithStandards', { params });
    if (result.code === '200') {
      productList.value = result.data.records;
      total.value = result.data.total;
      
      // 根据排序选项对商品进行排序
      if (sortOption.value === 'priceAsc') {
        productList.value.sort((a, b) => (a.specPrice * a.discount) - (b.specPrice * b.discount));
      } else if (sortOption.value === 'priceDesc') {
        productList.value.sort((a, b) => (b.specPrice * b.discount) - (a.specPrice * a.discount));
      } else if (sortOption.value === 'salesDesc') {
        productList.value.sort((a, b) => (b.sales || 0) - (a.sales || 0));
      }
    } else {
      ElMessage.error('获取商品列表失败');
    }
  } catch (error) {
    console.error('获取商品失败:', error);
    ElMessage.error('获取商品列表失败');
  }
};

// 选择分类
const selectCategory = (categoryId) => {
  selectedCategoryId.value = categoryId;
  currentPage.value = 1; // 重置页码
  loadProducts();
};

// 跳转到商品详情页
const goToProductDetail = (productId) => {
  router.push(`/userWeb/product/${productId}`);
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  loadProducts();
};

// 处理每页显示数量变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  loadProducts();
};

// 监听分类变化
watch(() => selectedCategoryId.value, () => {
  loadProducts();
});

// 监听路由参数变化，当搜索关键词变化时重新加载商品
watch(() => route.query.keyword, () => {
  currentPage.value = 1; // 重置页码
  loadProducts();
});

onMounted(() => {
  fetchCategories();
  loadProducts();
});
</script>

<style scoped>
.products-container {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.sidebar {
  width: 200px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
}

.sidebar-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.category-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.category-list li {
  padding: 10px 15px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.category-list li:hover {
  background-color: #f5f7fa;
  color: #409EFF;
}

.category-list li.active {
  background-color: #409EFF;
  color: #fff;
}

.category-list li:first-child {
  font-weight: bold;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
  padding-bottom: 15px;
}

.category-list li:first-child.active {
  background-color: #409EFF;
  color: #fff;
}

.main-content {
  flex: 1;
}

.products-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.products-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.product-card {
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  cursor: pointer;
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-img {
  height: 200px;
  overflow: hidden;
}

.product-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.product-card:hover .product-img img {
  transform: scale(1.05);
}

.product-info {
  padding: 15px;
}

.product-name {
  margin: 0 0 10px;
  font-size: 16px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.product-sales {
  font-size: 12px;
  color: #999;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 